/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.dao.ScheduleRebaseJobDao;
import io.renren.entity.ScheduleRebaseJobEntity;
import io.renren.service.ScheduleRebaseJobService;
import io.renren.utils.Constant;
import io.renren.utils.Query;
import io.renren.utils.ScheduleRebaseUtils;
import org.apache.commons.lang.StringUtils;
import org.quartz.Scheduler;
import org.quartz.SimpleTrigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("scheduleRebaseJobService")
public class ScheduleRebaseJobServiceImpl extends ServiceImpl<ScheduleRebaseJobDao, ScheduleRebaseJobEntity> implements ScheduleRebaseJobService,Runnable {

	@Qualifier("schedulerFactoryBean")
	@Autowired
    private Scheduler scheduler;

//	/**
//	 * 项目启动时，初始化定时器
//	 */
//	@PostConstruct
//	public void init(){
//		List<ScheduleRebaseJobEntity> scheduleJobList = this.list();
//		for(ScheduleRebaseJobEntity scheduleJob : scheduleJobList){
//			if (scheduleJob.getExecuteTime().getTime() - System.currentTimeMillis() < 0) {
//				continue;
//			}
//			SimpleTrigger simpleTrigger = ScheduleRebaseUtils.getSimpleTrigger(scheduler, scheduleJob.getJobId());
//			//如果不存在，则创建
//            if(simpleTrigger == null) {
//                ScheduleRebaseUtils.createScheduleJob(scheduler, scheduleJob);
//            }else {
//				ScheduleRebaseUtils.updateScheduleJob(scheduler, scheduleJob);
//            }
//		}
//	}
@Autowired
private RedisTemplate<String,String> redisTemplate;
	@Override
	public void run() {
		List<ScheduleRebaseJobEntity> scheduleJobList = this.list();
		for(ScheduleRebaseJobEntity scheduleJob : scheduleJobList){
			try {
				if (scheduleJob.getExecuteTime().getTime() - System.currentTimeMillis() < 0) {
					continue;
				}
				SimpleTrigger simpleTrigger = ScheduleRebaseUtils.getSimpleTrigger(scheduler, scheduleJob.getJobId());
				//如果不存在，则创建
				if(simpleTrigger == null) {
					ScheduleRebaseUtils.createScheduleJob(scheduler, scheduleJob);
				}else {
					ScheduleRebaseUtils.updateScheduleJob(scheduler, scheduleJob);
				}
			} catch (Exception e) {
				redisTemplate.boundListOps("schedule_exception").leftPush("定时任务数据异常:"+scheduleJob.getJobId());
				System.out.println("定时任务数据异常:"+scheduleJob.getJobId());
			}
		}
	}

	/**
	 * 项目启动时，初始化定时器
	 */
	@PostConstruct
	public void init() {
		new Thread(this).start();
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String beanName = (String)params.get("beanName");

		IPage<ScheduleRebaseJobEntity> page = this.page(
			new Query<ScheduleRebaseJobEntity>().getPage(params),
			new QueryWrapper <ScheduleRebaseJobEntity>().like(StringUtils.isNotBlank(beanName),"bean_name", beanName)
		);

		return new PageUtils(page);
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveJob(ScheduleRebaseJobEntity scheduleJob) {
//		scheduleJob.setCreateTime(new Date());
		scheduleJob.setStatus(Constant.ScheduleStatus.NORMAL.getValue());
        this.save(scheduleJob);

        ScheduleRebaseUtils.createScheduleJob(scheduler, scheduleJob);
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(ScheduleRebaseJobEntity scheduleJob) {
        ScheduleRebaseUtils.updateScheduleJob(scheduler, scheduleJob);

        this.updateById(scheduleJob);
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] jobIds) {
    	for(Long jobId : jobIds){
    		ScheduleRebaseUtils.deleteScheduleJob(scheduler, jobId);
    	}

    	//删除数据
    	this.removeByIds(Arrays.asList(jobIds));
	}

	@Override
    public int updateBatch(Long[] jobIds, int status){
    	Map<String, Object> map = new HashMap<>(2);
    	map.put("list", jobIds);
    	map.put("status", status);
    	return baseMapper.updateBatch(map);
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void run(Long[] jobIds) {
    	for(Long jobId : jobIds){
    		ScheduleRebaseUtils.run(scheduler, this.getById(jobId));
    	}
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void pause(Long[] jobIds) {
        for(Long jobId : jobIds){
    		ScheduleRebaseUtils.pauseJob(scheduler, jobId);
    	}

    	updateBatch(jobIds, Constant.ScheduleStatus.PAUSE.getValue());
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void resume(Long[] jobIds) {
    	for(Long jobId : jobIds){
    		ScheduleRebaseUtils.resumeJob(scheduler, jobId);
    	}

    	updateBatch(jobIds, Constant.ScheduleStatus.NORMAL.getValue());
    }

}
